package com.ada.opencv;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GetVideoFirstFrame {

    public static void main(String[] args) throws IOException {
        System.setProperty("java.library.path", "libs");
        System.loadLibrary(avutil.class.getName());

        System.setProperty("jna.library.path", "E:\\tools\\ffmpeg\\bin");
        String videoPath = "D:\\aa.mp4"; // 视频文件路径
        String savePath = "D:\\save.jpg"; // 首图保存路径

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage firstFrame = null;

        try {
            grabber.start();
            grabber.setFrameNumber(0); // 获取首帧

            firstFrame = converter.convert(grabber.grab());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                grabber.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (firstFrame != null) {
            File output = new File(savePath);
            ImageIO.write(firstFrame, "jpg", output);
        }
    }
}
